#pragma once

#include <sys/wait.h>
#include <unistd.h>
#include <functional>
#include "Common.hpp"
#include "ThreadPool.hpp"

using namespace ThreadPoolModule;

using namespace LogModule;

const int defaultsockfd = -1;
const int defaultbaklog = 8;

// using func_t = std::function<void()>;
using func_t = std::function<std::string(const std::string &, InetAddr &)>;

// 服务器不希望被拷贝或赋值
class TcpServer : public NoCopy
{
private:
    class ThreadData
    {
    public:
        ThreadData(int fd, InetAddr &ar, TcpServer *tr)
            : sockfd(fd), addr(ar), tsvr(tr)
        {
        }

    public:
        int sockfd;
        InetAddr addr;
        TcpServer *tsvr;
    };
    void Service(int sockfd, InetAddr &peer)
    {
        while (true)
        {
            char buffer[1024];
            // 读数据
            ssize_t n = read(sockfd, buffer, sizeof(buffer) - 1);
            if (n > 0)
            {
                buffer[n] = 0;

                std::string echo_string = _func(buffer, peer);
                // LOG(LogLevel::DEBUG) << peer.AddrToString() << " says# " << buffer;
                // // 写数据
                // std::string message = "echo# ";
                // message += buffer;

                n = write(sockfd, echo_string.c_str(), echo_string.size());
            }
            else if (n == 0)
            {
                LOG(LogLevel::DEBUG) << "退出了...";
                close(sockfd);
                break;
            }
            else
            {
                LOG(LogLevel::DEBUG) << "异常...";
                close(sockfd);
                break;
            }
        }
    }

public:
    TcpServer(uint16_t port, func_t func)
        : _listensockfd(defaultsockfd), _port(port), _isrunning(false), _func(func)
    {
    }

    void Init()
    {
        // 1.创建套接字
        _listensockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_listensockfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket error!";
            exit(SOCKET_ERR);
        }
        LOG(LogLevel::INFO) << "socket success, sockfd: " << _listensockfd;

        // 2.bind众所周知的主机信息
        InetAddr local("0", _port);
        int n = bind(_listensockfd, local.NetAddrPtr(), local.NetAddrLen());
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "bind error!";
            exit(BIND_ERR);
        }
        LOG(LogLevel::INFO) << "bind success, sockfd: " << _listensockfd;

        // 3.listen
        n = listen(_listensockfd, defaultbaklog);
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "listen error!";
            exit(LISTEN_ERR);
        }
        LOG(LogLevel::INFO) << "listen success, sockfd: " << _listensockfd;
    }

    static void *Routine(void *args)
    {
        pthread_detach(pthread_self());
        ThreadData *td = static_cast<ThreadData *>(args);
        td->tsvr->Service(td->sockfd, td->addr);

        delete td;
        return nullptr;
    }

    void Run()
    {
        _isrunning = true;
        while (_isrunning)
        {
            // accept获取连接
            sockaddr_in peer;
            socklen_t len = sizeof(peer);
            std::cout << "等待获得链接" << std::endl;
            int sockfd = accept(_listensockfd, CONV(peer), &len);
            if (sockfd < 0)
            {
                LOG(LogLevel::WARNING) << "accept fail!";
                exit(ACCEPT_ERR);
            }
            InetAddr addr(peer);
            LOG(LogLevel::INFO) << "accept success, peer :" << addr.AddrToString();

            // 线程池版本，线程池一般比较适合处理短服务
            // 将新链接和客户端构建一个新的任务，push线程池中
            // ThreadPool<func_t>::GetInstance()->Enqueue([this, sockfd, &addr](){
            //     this->Service(sockfd, addr);
            // });

            // 多线程版本
            ThreadData *td = new ThreadData(sockfd, addr, this);
            pthread_t tid;
            int n = pthread_create(&tid, nullptr, Routine, td);
            if (n < 0)
            {
                LOG(LogLevel::WARNING) << "pthread_create fail!";
                exit(PTHREAD_CREATE_ERR);
            }
            // 多进程版本
            //  pid_t pid = fork();
            //  if (pid < 0)
            //  {
            //      std::cerr << "fork error!";
            //      exit(FORK_ERR);
            //  }
            //  else if (pid == 0)
            //  {
            //      // child
            //      close(_listensockfd);

            //     if(fork() > 0)  //grandchild - 孤儿进程，1，被系统领养
            //         exit(OK);

            //     Service(sockfd, addr);
            //     exit(OK);
            // }
            // else
            // {
            //     // father
            //     close(sockfd);
            //     pid_t rid = waitpid(pid, nullptr, 0);
            //     (void)rid;
            // }
        }
        _isrunning = false;
    }

    ~TcpServer() {}

private:
    int _listensockfd; // 监听
    uint16_t _port;

    bool _isrunning;

    func_t _func;    //业务处理
};